package hottargui.standard;

import java.util.Iterator;
import java.util.Map;

import hottargui.framework.*;

public class StandardEndRoundState implements TarguiState {

	Game gameContext;
	
	public StandardEndRoundState(Game game)
	{
		this.gameContext = game;
	}
	
	public boolean buy(int count, Position deploy) throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public State getState() {
		return State.endRound;
	}

	public PlayerColor getWinner() throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public boolean move(Position from, Position to, int count) throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public void newGame() throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public void rollDie() throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public PlayerColor turnCard() throws IllegalActionException {
		
		TurnSequenceStrategy tss = gameContext.getGameObjectServer().getTurnSequenceStrategy();
		GameData gd = gameContext.getGameObjectServer().getGameData();
		
		Map<PlayerColor, Player> players = gd.getPlayers();
		
		for (Iterator<? extends Tile> tileIterator = gameContext.getBoardIterator(); tileIterator.hasNext(); ) 
		{
			Tile thisTile = (Tile) tileIterator.next();
			
			if ( thisTile.getOwnerColor() != PlayerColor.None )
			{
				Player thisPlayer = players.get(thisTile.getOwnerColor());
				
				// check for player owning settlement
				Tile settlement = gameContext.getTile(((StandardPlayer)thisPlayer).getSettlement());
				if ( settlement.getOwnerColor() == thisPlayer.getColor() )
				{
					((StandardPlayer)thisPlayer).add(thisTile.getType().getEconomicValue());
				}
			}
			
		}
		
		if ( gd.getRoundsLeft() == 0 )
		{
			gameContext.setState(gameContext.getFactory().getEndGameState(gameContext));
			return PlayerColor.None; // TODO: ???
		}
		else
		{
			gameContext.setState(gameContext.getFactory().getMoveState(gameContext));
			gd.decreaseRoundsLeft();
			return gd.setPlayerInTurn(tss.nextPlayer());
		}
	}

}
